package com.mianyang.zhangsan.plugin.export;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.mianyang.zhangsan.plugin.export.parse.HtmlParse;
import com.mianyang.zhangsan.plugin.export.plugin.font.CustomXmlWorkerFontProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author jiangjr
 * @date 2022-10-13
 */
@Slf4j
public class PdfTemplate extends AbstractTemplate{
    private final HtmlParse parse;
    private String htmlSource;

    public PdfTemplate(String path) {
        setHtmlSource(path);
        parse = new HtmlParse(htmlSource);
    }

    public void setHtmlSource(String path) {
        InputStream in = null;
        StringBuilder sb = new StringBuilder();
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            in = new FileInputStream(path);
            while ((len = in.read(buffer)) > 0) {
                sb.append(new String(buffer, 0 , len));
            }
        }catch (IOException e) {
            log.error("文件读取异常");
            throw new RuntimeException("文件读取异常");
        }finally {
            try {
                if (in != null){
                    in.close();
                }
            } catch (IOException e) {
                log.error("文件流关闭异常");
            }
        }
        this.htmlSource = sb.toString();
    }

    @Override
    public void fill() {
        Map<String, Object> variable = getVariable();
        for (Map.Entry<String, Object> entry : variable.entrySet()) {
            parse.combination(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public OutputStream generator() {
        Document document = new Document();
        OutputStream out = new ByteArrayOutputStream();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(this.htmlSource.getBytes(StandardCharsets.UTF_8)), null,
                    StandardCharsets.UTF_8, new CustomXmlWorkerFontProvider());
        } catch (DocumentException | IOException e) {
            // 异常处理
            log.error("pdf模板生成异常");
            throw new RuntimeException("pdf模板生成异常");
        }
        document.close();
        return out;
    }
}
